<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择分类" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="色系" prop="color">
        <el-select v-model="queryParams.color" placeholder="请选择色系" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否私有" prop="provate">
        <el-select v-model="queryParams.provate" placeholder="请选择是否私有" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['module:wpWallpaperList:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['module:wpWallpaperList:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['module:wpWallpaperList:remove']"
        >删除</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="Download"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['module:wpWallpaperList:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-radio-group
            v-model="listType"
            @change="handleListType"
        >
          <el-radio-button label=true >详情</el-radio-button>
          <el-radio-button label=false >略缩图</el-radio-button>
        </el-radio-group>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    {{ids}}

    <div v-show="listType">
      <el-table v-loading="loading" :data="wpWallpaperListList" @selection-change="handleSelectionChange" >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="壁纸名" align="center" prop="name" min-width="82px">
          <template #default="scope">
            <el-tooltip placement="top">
              <span>{{ scope.row.name }}</span>
              <template #content>
                <el-image :src="scope.row.url" style="width: 200px"/>
              </template>
            </el-tooltip>
          </template>
        </el-table-column>

        <!--        <el-table-column label="壁纸名" align="center" prop="name" >-->
        <!--          <template #default="scope">-->
        <!--            <el-tooltip class="item" effect="dark" content="这是日期" placement="top">-->
        <!--              <span>{{ scope.row.name }}</span>-->
        <!--            </el-tooltip>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <el-table-column label="分类" align="center" prop="type" />
        <el-table-column label="色系" align="center" prop="color" />
        <el-table-column label="下载量" align="center" prop="downloads" />
        <el-table-column label="大小" align="center" prop="size" />
        <el-table-column label="分辨率" align="center" prop="resolution" />
        <el-table-column label="收藏量" align="center" prop="star" />
        <el-table-column label="标签" align="center" prop="tag" />
        <el-table-column label="是否私有" align="center" prop="provate" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['module:wpWallpaperList:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['module:wpWallpaperList:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="mt-4" v-show="!listType">
      <!--      <el-row :gutter="10">-->
      <!--          <el-col :span="4" >-->
      <!--            <el-checkbox-group-->
      <!--                v-for="item in wpWallpaperListList"-->
      <!--                v-loading="loading"-->
      <!--                v-model="selections"-->
      <!--            >-->
      <!--            <el-card shadow="hover">-->
      <!--              <el-tooltip>-->
      <!--                &lt;!&ndash;鼠标经过时文字提示&ndash;&gt;-->
      <!--                <template #content>-->
      <!--                  <div class="c-tooltip">-->
      <!--                    {{item.type}} <br/>-->
      <!--                    {{item.color}} <br/>-->
      <!--                    {{item.downloads}} <br/>-->
      <!--                    {{item.resolution}}-->
      <!--                  </div>-->
      <!--                </template>-->
      <!--                <el-checkbox style="width: auto; height: auto" :key="item.id" :label="item" :value="item.id"  is-checked="true" >-->
      <!--                  <el-image :src="item.url" />-->
      <!--                </el-checkbox>-->
      <!--              </el-tooltip>-->
      <!--            </el-card>-->
      <!--            </el-checkbox-group>-->
      <!--          </el-col>-->
      <!--      </el-row>-->

      <el-checkbox-group
          v-loading="loading"
          v-model="selections"
          v-for="item in wpWallpaperListList"
          @click="handleSelectionChangeToCheckBox(item)"
          @change="cha"
      >
        <el-checkbox style="width: 100px; height: auto" :key="item.id" :label="item" :value="item.id" >
          <el-image :src="item.url" />
        </el-checkbox>
      </el-checkbox-group>
    </div>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改壁纸对话框 -->
    <el-dialog :title="title" v-model="open" width="60%" append-to-body>
      <el-form ref="wpWallpaperListRef" :model="form" :rules="rules" label-width="15%">
        <div class="mt-4">
          <div class=" wt50">
            <el-form-item label="分类" prop="typeId">
              <el-radio-group v-model="form.typeId" placeholder="请选择分类" class="ai-c " >
                <el-radio
                    v-for="item in wpTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="色系" prop="colorId">
              <el-radio-group v-model="form.colorId" placeholder="请选择色系" class="ai-c " >
                <el-radio class="box-1"
                          v-for="item in wpColorList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                          :style="{backgroundColor: item.codes}"
                ></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="壁纸链接" prop="url">
              <el-input v-model="form.url" placeholder="请输入内容" disabled/>
            </el-form-item>
            <el-form-item label="下载量" prop="downloads" v-if="form.id == null">
              <el-input v-model="form.downloads" placeholder="请输入下载量" />
            </el-form-item>
            <el-form-item label="收藏量" prop="star">
              <el-input v-model="form.star" placeholder="请输入收藏量" />
            </el-form-item>
            <el-form-item label="大小" prop="size">
              <el-input v-model="form.size" placeholder="请输入大小" />
            </el-form-item>
            <el-form-item label="分辨率" prop="resolution">
              <el-input v-model="form.resolution" placeholder="请输入分辨率" />
            </el-form-item>
            <el-form-item label="标签" prop="tag">
              <el-input v-model="form.tag" placeholder="请输入标签" />
            </el-form-item>
            <el-form-item label="是否私有" prop="provate">
              <el-radio-group v-model="form.provate">
                <el-radio
                    v-for="dict in sys_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </div>
          <div class="wh100">
            <el-form-item>
              <!-- 壁纸上传 -->
              <!--            <uploadImage />-->
              <el-upload
                  class="upload-demo"
                  active="D:/wp/uploadPath/"
                  :http-request="httpRequest"
                  :before-upload="beforeUpload"
                  :before-remove="beforeRemove"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-remove="handleRemove"
                  list-type="picture"
                  drag
                  multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg，且壁纸不超过【20MB】</div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    {{uploadImage}}
  </div>
</template>

<script setup name="WpWallpaperList">
import { listWpWallpaperList, getWpWallpaperList, delWpWallpaperList, addWpWallpaperList, updateWpWallpaperList } from "@/api/module/wpWallpaperList";
import { listWpType } from "@/api/module/wpType";
import { listWpWallpaperColor } from "@/api/module/wpWallpaperColor";
import uploadImage from "./uploadImage";
import {ElMessage} from "element-plus";

const { proxy } = getCurrentInstance();
const { sys_yes_no } = proxy.useDict('sys_yes_no');

const wpWallpaperListList = ref([]);
const wpTypeList = ref([]);
const wpColorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const listType = ref(true); // 切换列表详细信息或略缩图
const selections = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    typeId: null,
    color: null,
    provate: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询壁纸列表列表 */
function getList() {
  loading.value = true;
  listWpWallpaperList(queryParams.value).then(response => {
    wpWallpaperListList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    typeId: null,
    url: null,
    color: null,
    downloads: null,
    size: null,
    resolution: null,
    star: null,
    tag: null,
    provate: null,
    createTime: null,
    createAt: null,
    remark: null
  };
  proxy.resetForm("wpWallpaperListRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.info("handleSelectionChange -> selection", selection)
  console.info("handleSelectionChange -> selection.id", selection.map(item => item.id))
  selections.value = selection;
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 略缩图中多选框点击触发事件
function handleSelectionChangeToCheckBox(selection){
  console.info("handleSelectionChangeToCheckBox -> selection", selection)
  selections.value.push(selection);
  console.info("handleSelectionChangeToCheckBox -> selections", selections.value)

  // ids.value = selection.map(item => item.id);
}

function cha(){
  console.info("cha")
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加新壁纸";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getWpWallpaperList(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改壁纸详情";
  });


}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["wpWallpaperListRef"].validate(valid => {
    console.info(form)
    if (valid) {
      if (form.value.id != null) {
        updateWpWallpaperList(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWpWallpaperList(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除壁纸列表编号为"' + _ids + '"的数据项？').then(function() {
    return delWpWallpaperList(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 获取颜色、类型数据
function getBase(){
  listWpWallpaperColor().then( res => {
    wpColorList.value = res.rows;
  });
  listWpType().then( res => {
    wpTypeList.value = res.rows;
  });
}

// true 为详情模式，false 为略缩图模式
function handleListType(boo) {
  listType.value = JSON.parse(boo);
}

// ----------------------------- 图片上传相关操作 start -----------------------------

// 图片预处理
function beforeUpload(file){
  console.info("beforeUpload");

  /**
   * 图片上传前预处理，主要验证图片 格式、 大小
   * 大小不可超 20M，单位为字节（B），file.size 获取的单位为 B ，20M 换成 B 为 20971520B
   * 格式为 jpg， jpeg， png
   */
      // 图片大小
  let wpsize = file.size.toFixed(2);
  if (wpsize > 20971520) {
    // console.info("图片大小超过 20M ，请调整后重新上传")
    handleError("图片大小超过 20M ，请调整后重新上传");
  }
  // 验证图片格式
  if (file.type.indexOf("image/") == -1){
    handleError("图片格式不是 “png”、“jpg”、“jpeg”格式 ，请调整后重新上传");
    handleRemove(file);
  }{
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      console.info(reader)
      // options.img = reader.result;
      // options.filename = file.name;
    };
  }
  // console.info(img);
  // const img = new Image();
  // img.src = file.name;
  //
  //
  // img.src = "https://haowallpaper.com/link/common/file/getCroppingImg/16449394311089536";
  // img.onload = () => {
  //   const canvas = this.$refs.canvas;
  //   const ctx = canvas.getContext('2d');
  //   canvas.width = img.width; // 设置canvas宽度为图片宽度
  //   canvas.height = img.height; // 设置canvas高度为图片高度
  //   ctx.drawImage(img, 0, 0); // 将图片绘制到canvas上
  //   console.log(img.width, img.height); // 获取图片尺寸
  // };
  //
  //
  // console.info(img.width, img.height);
  // console.info(file);
}

function beforeRemove(){
  console.info("beforeRemove");
}

function handleSuccess(response, file, fileList) {
  console.log('上传成功', response);
}

// 上传失败
function handleError(err) {
  console.error('handleError--->');
  // console.error('上传失败', err);
  ElMessage({ message: err, type: 'error' });
}

// 移除图片
function handleRemove(file) {
  console.log("handleRemove");
}
// 预览图片
function handlePreview(file) {
  console.info("handlePreview", file);
}

// 上传图片
// function handleUpload(data){
//   console.info("handleUpload", data);
//   handleUploadWp().then(res => {
//     console.info(res)
//   })
// }

// 覆盖默认上传行为
function httpRequest(){
  console.info("覆盖默认上传行为--httpRequest");
}


// ----------------------------- 图片上传相关操作  end  -----------------------------

getList();
getBase();
</script>

<style>
.c-tooltip {
  //position: absolute;
  //color: #fff;
  //background-color: rgba(0, 0, 0, 0.26);
}
</style>